# 设置错误时停止执行
$ErrorActionPreference = "Stop"

$commonPropsPath = Join-Path $PSScriptRoot "../common.props"

# 获取当前 ABP 版本
function Get-CurrentAbpVersion {
    $commonProps = Get-Content $commonPropsPath -Raw
    if ($commonProps -match '<AbpVersion>([\d\.]+)</AbpVersion>') {
        return $matches[1]
    }
    throw "无法从 common.props 中获取 ABP 版本"
}

# 获取当前 .NET 版本
function Get-CurrentDotNetVersion {
    $commonProps = Get-Content $commonPropsPath -Raw
    if ($commonProps -match '<DotNetVersion>([\d\.]+)</DotNetVersion>') {
        return $matches[1]
    }
    throw "无法从 common.props 中获取 .NET 版本"
}

# 获取最新的 ABP 版本
function Get-LatestAbpVersion {
    $nugetApiUrl = "https://api.nuget.org/v3/registration5-semver1/volo.abp.core/index.json"
    $response = Invoke-RestMethod -Uri $nugetApiUrl
    $latestVersion = $response.items[-1].upper
    return $latestVersion
}

# 获取 ABP 版本对应的 .NET 版本
function Get-DotNetVersionForAbp {
    param (
        [string]$abpVersion
    )
    
    # 获取主版本号
    $majorVersion = [int]($abpVersion -split '\.')[0]
    
    # 根据主版本号确定 .NET 版本
    switch ($majorVersion) {
        8 { return "8.0" }
        9 { return "9.0" }
        10 { return "10.0" }
        default { throw "不支持的 ABP 版本: $abpVersion" }
    }
}

# 更新 ABP 版本和 .NET 版本
function Update-Versions {
    param (
        [string]$newAbpVersion,
        [string]$newDotNetVersion
    )
    $content = Get-Content $commonPropsPath -Raw
    
    # 更新 ABP 版本
    $content = $content -replace '<AbpVersion>[\d\.]+</AbpVersion>', "<AbpVersion>$newAbpVersion</AbpVersion>"
    
    # 更新版本后缀
    $content = $content -replace '<VersionSuffix>abp[\d\.]+</VersionSuffix>', "<VersionSuffix>abp$newAbpVersion</VersionSuffix>"
    
    # 更新 .NET 版本
    $content = $content -replace '<DotNetVersion>[\d\.]+</DotNetVersion>', "<DotNetVersion>$newDotNetVersion</DotNetVersion>"
    $content = $content -replace '<TargetFrameworks>net[\d\.]+</TargetFrameworks>', "<TargetFrameworks>net$newDotNetVersion</TargetFrameworks>"
    
    Set-Content -Path $commonPropsPath -Value $content
}

# 主逻辑
try {
    $currentAbpVersion = Get-CurrentAbpVersion
    $currentDotNetVersion = Get-CurrentDotNetVersion
    $latestAbpVersion = Get-LatestAbpVersion
    $newDotNetVersion = Get-DotNetVersionForAbp -abpVersion $latestAbpVersion

    Write-Host "当前 ABP 版本: $currentAbpVersion"
    Write-Host "当前 .NET 版本: $currentDotNetVersion"
    Write-Host "最新 ABP 版本: $latestAbpVersion"
    Write-Host "对应的 .NET 版本: $newDotNetVersion"

    if ($currentAbpVersion -ne $latestAbpVersion) {
        Write-Host "发现新版本，开始更新..."
        
        # 更新版本
        Update-Versions -newAbpVersion $latestAbpVersion -newDotNetVersion $newDotNetVersion
        
        Write-Host "更新完成！"
    } else {
        Write-Host "当前已是最新版本"
    }
} catch {
    Write-Error "发生错误: $_"
    exit 1
} 